package com.fenghuajueli.libbasecoreui.widget;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import com.fenghuajueli.libbasecoreui.dialog.CommonTipsDialog;
import com.ll.permission.AllowPermissionUseCase;
import com.permissionx.guolindev.callback.RequestCallback;

import java.util.ArrayList;
import java.util.List;

import im.delight.android.webview.AdvancedWebView;

public class CustomerWebview extends AdvancedWebView {
    private ProgressView progressView;//进度条

    private FragmentActivity activity;

    public CustomerWebview(Context context) {
        super(context);
        init();
    }

    public CustomerWebview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomerWebview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //初始化进度条
        progressView = new ProgressView(getContext());
        progressView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(getContext(), 4)));
        progressView.setColor(Color.BLUE);
        progressView.setProgress(10);
        //把进度条加到Webview中
        addView(progressView);

        WebSettings settings = getSettings();
        settings.setAllowUniversalAccessFromFileURLs(false);
        settings.setAllowFileAccessFromFileURLs(false);
        settings.setJavaScriptEnabled(true);

        setWebChromeClient(new MyWebCromeClient());

    }

    private class MyWebCromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                //加载完毕进度条消失
                progressView.setVisibility(View.GONE);
            } else {
                //更新进度
                progressView.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

    }

    @Override
    protected void openFileInput(ValueCallback<Uri> fileUploadCallbackFirst, ValueCallback<Uri[]> fileUploadCallbackSecond, boolean allowMultiple) {
        openFile(fileUploadCallbackFirst, fileUploadCallbackSecond, allowMultiple);
    }

    private void openFile(ValueCallback<Uri> fileUploadCallbackFirst, ValueCallback<Uri[]> fileUploadCallbackSecond, boolean allowMultiple) {
        AllowPermissionUseCase.useGallery(
                (AppCompatActivity) getContext(),
                "相册权限",
                "用于反馈图片上传功能，需要访问您的相册权限，如若拒绝，将无法使用上述功能。",
                "相册权限：该功能需要相册权限才可以正常运行，用于上传反馈图片。",
                "openFile",
                "请先申请相册权限!",
                () -> {
                    CustomerWebview.super.openFileInput(fileUploadCallbackFirst, fileUploadCallbackSecond, allowMultiple);
                    return null;
                });
    }

    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            int g1 = ((AppCompatActivity) getContext()).checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES);
            int g2 = ((AppCompatActivity) getContext()).checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO);
            return g1 == PackageManager.PERMISSION_GRANTED && g2 == PackageManager.PERMISSION_GRANTED;
        } else {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                int g1 = ((AppCompatActivity) getContext()).checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                return g1 == PackageManager.PERMISSION_GRANTED;
            }
        }
        return false;
    }

    private CommonTipsDialog getConfirmDialog() {
        return new CommonTipsDialog(getContext(), "图片选取需要申请相册权限才能使用", "以后再说", "同意");
    }

    private String[] getPermissionArray() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO};
        } else {
            return new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        }
    }


    /**
     * dp转换成px
     *
     * @param context Context
     * @param dp      dp
     * @return px值
     */
    private int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

}
